package com.shwread.android.qysw.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.ciko.code.http.BaseResponse;
import com.ciko.code.http.HttpClient;
import com.ciko.code.http.HttpResponseListener;
import com.ciko.code.http.Req.FieldAttendanceReq;
import com.mywork.activity.AttendanceRecordActivity2;
import com.shwread.android.qysw10000192.R;

import java.text.SimpleDateFormat;
import java.util.Date;

import logic.util.Util;


public class FieldAttendanceActivity
        extends
        Activity
        implements
        View.OnClickListener,
        HttpResponseListener
{
	
	private TextView                  txt_date;
	private TextView                  txt_record;
	private Button                    btn_ok;
	private LinearLayout              lin_mapview;
	private EditText                  et_reason;
	private EditText                  et_name;
	private static TextView           txt_drr;
	
	private static String             custAddr;
	private static Double             custLon;
	private static Double             custLat;
	private static String             actualAddr;
	private static Double             actualLon;
	private static Double             actualLat;
	private static ImageView          img_back;
	
	private static AMapLocationClient mLocationClient   = null;
	private AMapLocationListener      mLocationListener = null;
	private AMapLocationClientOption  mLocationOption   = null;
	private String                    title             = "";
	private TextView                  tvTitle;
	//    private Double lon;
	//    private Double lat;
	//    private String drr;
	//    private String city;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_field_attendance);
		//        //透明状态栏
		//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		//        //透明导航栏
		//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
		if (getIntent().getExtras().containsKey("title")) {
			title = getIntent().getStringExtra("title");
		}
		intiView();
		
		mLocationClient = new AMapLocationClient(getApplicationContext());
		
		mLocationOption = new AMapLocationClientOption();
		//初始化定位参数
		mLocationOption = new AMapLocationClientOption();
		//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
		mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
		//设置是否返回地址信息（默认返回地址信息）
		mLocationOption.setNeedAddress(true);
		//设置是否只定位一次,默认为false
		mLocationOption.setOnceLocation(false);
		//设置是否强制刷新WIFI，默认为强制刷新
		mLocationOption.setWifiActiveScan(true);
		//设置是否允许模拟位置,默认为false，不允许模拟位置
		mLocationOption.setMockEnable(false);
		//设置定位间隔,单位毫秒,默认为2000ms
		mLocationOption.setInterval(2000);
		//给定位客户端对象设置定位参数
		mLocationClient.setLocationOption(mLocationOption);
		//启动定位
		
		mLocationListener = new AMapLocationListener()
		{
			@Override
			public void onLocationChanged(final AMapLocation aMapLocation) {
				if (aMapLocation != null && aMapLocation.getErrorCode() == 0)
				{
					txt_drr.post(new Runnable()
					{
						@Override
						public void run() {
							txt_drr.setText(aMapLocation.getAddress());
							
							custLat = aMapLocation.getLatitude();
							custLon = aMapLocation.getLongitude();
							custAddr = aMapLocation.getAddress();
							actualAddr = aMapLocation.getAddress();
							actualLon = aMapLocation.getLongitude();
							actualLat = aMapLocation.getLatitude();
							
							// Log.i("into==============", custLat + "," + custLon + "," + custAddr + "," + actualLat + "," + actualLon + "," + actualLat);
						}
					});
					
					mLocationClient.stopLocation();
				}
				else
				{
					
				}
			}
		};
		mLocationClient.setLocationListener(mLocationListener);
		mLocationClient.startLocation();
		
	}
	
	/**
	 * 初始化控件
	 */
	private void intiView() {
		tvTitle = (TextView) findViewById(R.id.tv_title);
		tvTitle.setText(title);
		txt_date = (TextView) findViewById(R.id.txt_date);
		img_back = (ImageView) findViewById(R.id.img_back);
		txt_record = (TextView) findViewById(R.id.txt_record);
		btn_ok = (Button) findViewById(R.id.btn_ok);
		lin_mapview = (LinearLayout) findViewById(R.id.lin_mapview);
		et_reason = (EditText) findViewById(R.id.et_reason);
		et_name = (EditText) findViewById(R.id.et_name);
		txt_drr = (TextView) findViewById(R.id.txt_drr);
		
		//监听控件
		lin_mapview.setOnClickListener(this);
		btn_ok.setOnClickListener(this);
		btn_ok.setClickable(false);
		txt_record.setOnClickListener(this);
		img_back.setOnClickListener(this);
		
		long time = System.currentTimeMillis();
		Date date = new Date(time);
		SimpleDateFormat format = new SimpleDateFormat("MM月dd日 HH:mm");
		txt_date.setText(format.format(date));
		
		et_name.addTextChangedListener(new TextWatcher()
		{
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				
			}
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
				if (s.length() > 0 && et_reason.getText().length() > 0)
				{
					btn_ok.setBackgroundResource(R.drawable.renbao_btn_bg);
					btn_ok.setClickable(true);
				}
				else
				{
					btn_ok.setBackgroundResource(R.drawable.btn_on);
					btn_ok.setClickable(false);
				}
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				
			}
		});
		
		et_reason.addTextChangedListener(new TextWatcher()
		{
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				
			}
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
				if (s.length() > 0 && et_name.getText().length() > 0)
				{
					btn_ok.setBackgroundResource(R.drawable.renbao_btn_bg);
					btn_ok.setClickable(true);
				}
				else
				{
					btn_ok.setBackgroundResource(R.drawable.btn_on);
					btn_ok.setClickable(false);
				}
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				
			}
		});
	}
	
	@Override
	public void onClick(View v) {
		int i = v.getId();
		if (i == R.id.img_back)
		{
			finish();
			
		}
		else if (i == R.id.txt_record)
		{//查看签到记录
//			startActivity(new Intent(FieldAttendanceActivity.this, AttendanceRecordActivity.class));
			//二期新需求，要显示我的外勤，我收到的外勤
			startActivity(new Intent(FieldAttendanceActivity.this, AttendanceRecordActivity2.class));

		}
		else if (i == R.id.btn_ok)
		{//确定签到
			// FieldAttendanceAction fa = new FieldAttendanceAction();
			if (et_name.getText().toString().trim().length() > 20)
			{
				Util.showToast(FieldAttendanceActivity.this, "客户名称不能超过20字");
				return;
			}
			if (et_reason.getText().toString().trim().length() > 50)
			{
				Util.showToast(FieldAttendanceActivity.this, "拜访缘由不能超过50字");
				return;
			}
			
			if (TextUtils.isEmpty(et_name.getText().toString().trim()))
			{
				Util.showToast(FieldAttendanceActivity.this, "请输入客户名称");
				return;
			}
			if (TextUtils.isEmpty(et_reason.getText().toString().trim()))
			{
				Util.showToast(FieldAttendanceActivity.this, "请输入拜访缘由");
				return;
			}
			// Log.i("into123==============", custLat + "," + custLon + "," + custAddr + "," + actualLat + "," + actualLon + "," + actualLat);
			doHttpResqust();
			btn_ok.setClickable(false);
			
		}
		else if (i == R.id.lin_mapview)
		{//跳转到高德地图
		
			Intent intent = new Intent(FieldAttendanceActivity.this, AttendanceViewMap.class);
			startActivity(intent);
			
		}
	}
	
	//延迟2s在跳转
	Handler mHandler = new Handler()
	                 {
		                 @Override
		                 public void handleMessage(Message msg) {
			                 super.handleMessage(msg);
			                 if (msg.what == 1)
			                 {
				                 SystemClock.sleep(2000);//延时两秒执行finish
				                 finish();
			                 }
		                 }
	                 };
	
	public void doHttpResqust() {
		//String custName, String custAddr, String reason, Double custLon, Double custLat, String actualAddr, Double actualLon, Double actualLat
		HttpClient.getInstance(this).post(new FieldAttendanceReq(et_name.getText().toString(), txt_drr.getText().toString(), et_reason.getText().toString(), custLon, custLat, actualAddr, actualLon, actualLat), this);
	}
	
	@Override
	public void onRequestStart(String tag) {
		
	}
	
	@Override
	public void onResponseSuccess(BaseResponse<?> response, String tag) {
		String value = response.getReturnObject().toString();
		Util.showToast(this, value);
		btn_ok.setClickable(true);
		Message msg = new Message();
		msg.what = 1;
		mHandler.sendMessage(msg);
	}
	
	@Override
	public void onResponseFail(String tag, int resultCode) {
		Util.showToast(this, "加载失败，请重试");
		btn_ok.setClickable(true);
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		if (mLocationClient != null) mLocationClient.stopLocation();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mLocationClient != null) mLocationClient.onDestroy();
	}
	
	//    @Override
	//    protected void onSaveInstanceState(Bundle outState) {
	//        super.onSaveInstanceState(outState);
	//        //用于保存数据在onStop之前触发
	//        outState.putString("custAddr", custAddr);
	//        outState.putDouble("custLon", custLon);
	//        outState.putDouble("custLat", custLat);
	//
	//        outState.putString("actualAddr", actualAddr);
	//        outState.putDouble("actualLon", actualLon);
	//        outState.putDouble("actualLat", actualLat);
	//    }
	//
	//    @Override
	//    protected void onRestoreInstanceState(Bundle savedInstanceState) {
	//        super.onRestoreInstanceState(savedInstanceState);
	//        //用于读取数据在onResume之前触发与上面的onSaveInstanceState是一对兄弟
	//        txt_drr.setText(savedInstanceState.getString("custAddr"));
	//    }
	
	//    public static void getParameter(String custAddr1, Double custLon1, Double custLat1, String actualAddr1, Double actualLon1, Double actualLat1) {
	//        custAddr = custAddr1;
	//        custLon = custLon1;
	//        custLat = custLat1;
	//        actualAddr = actualAddr1;
	//        actualLon = actualLon1;
	//        actualLat = actualLat1;
	//        if (TextUtils.isEmpty(custAddr)) {
	//            mLocationClient.startLocation();
	//        }
	//        txt_drr.setText(custAddr1);
	//    }
	
}
